<template>
  <div>
    <NavTop>
      <div class="navtop-title">{{ $route.params.type }}</div>
    </NavTop>
    <BackBtn />
    <div class="content">
      <van-form @submit="onSubmit">
        <!-- 头像上传 -->
        <van-field name="uploader" label="头像">
            <template #input>
                <van-uploader 
                    v-model="updateInfo.fileList" 
                    multiple 
                    accept="image/*"
                    :max-count="1"
                    :before-read="beforeRead"
                    :after-read="afterRead"
                />
            </template>
        </van-field>
        <!-- 昵称 -->
        <van-field
          v-model="updateInfo.nick"
          name="nick"
          label="昵称"
          placeholder="请设置您的昵称"
          :rules="[{ required: true }]"
          autocomplete="off"
          maxlength="15"
        />
        <!-- 性别 -->
        <van-field name="sex" label="性别">
          <template #input>
            <van-radio-group v-model="updateInfo.sex" direction="horizontal">
              <van-radio name="男">男</van-radio>
              <van-radio name="女">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <!-- 生日 -->
        <van-field
          readonly
          clickable
          name="birthday"
          v-model="updateInfo.birthday"
          label="生日"
          placeholder="点击选择您的生日"
          @click="showPicker = true"
        />
        <van-popup v-model="showPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年/月/日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>
        <!-- 个性签名 -->
        <van-field
          v-model="updateInfo.sign"
          name="sign"
          rows="2"
          autosize
          label="个性签名"
          type="textarea"
          maxlength="50"
          placeholder="请输入您的个性签名"
          show-word-limit
        />
        <div style="margin: .2133rem">
          <van-button round block type="info" native-type="submit"
            >保存</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import NavTop from "@/components/NavTop"
import BackBtn from "@/components/BackBtn"
import { Toast } from 'vant'
import { reqUploadUserPic, reqGetUserhome, reqUpdateUserInfo } from '@/api'
import { mapState, mapMutations } from "vuex"
export default {
  components: {
    NavTop,
    BackBtn
  },
  data() {
    return {
      updateInfo: {
        nick: "",
        sex: "", // 性别
        birthday: "",
        sign: "", // 个性签名
        fileList: []
      },
      minDate: new Date(1900, 1, 1),
      maxDate: new Date(2099, 12, 31),
      currentDate: new Date(),
      showPicker: false,
      userImgUrl: ''
    }
  },
  computed: {
    ...mapState({
        userId: state => state.login.userInfo._id
    })
  },
  methods: {
    ...mapMutations('login', ['setUserInfo']),
    // 保存按钮回调
    async onSubmit(values) {
      const { nick, sex, birthday, sign } = values
      // /user_pic1.jpeg => 男  /user_pic2.jpeg => 女
      const defaultUserImg = sex === '男' ? '/user_pic1.jpeg' : '/user_pic2.jpeg'
      let obj = {
        _id: this.userId,
        nick, sex, birthday, sign,
        imgUrl: values.uploader.length ? this.userImgUrl : defaultUserImg
      }
      let res = await reqUpdateUserInfo(obj)
      if (res.status ===  200) {
        let oldUserInfo = this.$store.state.login.userInfo
        const { phone, _id, token } = oldUserInfo
        let newUserInfo = {
          _id,
          phone,
          nick,
          imgUrl: values.uploader.length ? this.userImgUrl : defaultUserImg,
          token
        }
        // 将修改的信息更新vuex
        this.setUserInfo(newUserInfo)
        // 更新本地存储
        localStorage.setItem('userInfo', JSON.stringify(newUserInfo))
      }
      Toast(res.msg)
    },
    // 选择生日确定的回调
    onConfirm(time) {
      this.currentDate = time
      this.updateInfo.birthday = this.formatterDateTime(this.currentDate)
      this.showPicker = false
    },
    // 格式化时间函数
    formatterDateTime(time) {
      let date = time
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      return year + "-" + month + "-" + strDate
    },
    // 获取用户信息
    async getUserHomeInfo() {
        let _id = this.userId
        let urlId = this.$route.query._id
        let res = await reqGetUserhome({_id, urlId})
        if (res.status === 200) {
            let updateObj = res.data.user
            updateObj.fileList = []
            updateObj.fileList.push({
                url: this.$baseUrl + res.data.user.imgUrl
            })
            this.updateInfo = updateObj
            this.userImgUrl = res.data.user.imgUrl
        }
    },
    // 上传图片类型（返回布尔值）
    beforeRead(file) {
      if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg') {
        return true
      }
      Toast('请上传 jpg、png 或 jpeg 格式图片')
      return false
    },
    // 图片上传
    async afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      let form = new FormData()
      form.append('file', file.file)
      try {
        let _id = this.$route.query._id
        let res = await reqUploadUserPic(form, {_id})
        if (res.res_code === '0') {
            file.status = 'done'
            file.message = '上传成功'
            this.userImgUrl = res.url
            Toast('头像修改成功')
        } else {
            file.status = 'failed'
            file.message = '上传失败'
        }
      } catch (error) {
        file.status = 'failed'
        file.message = '上传失败'
      }
    }
  },
  mounted() {
    this.getUserHomeInfo()
  }
}
</script>

<style lang="less" scoped></style>
